#include "xmppcore/stanzaparser.h"
#include "xmppcore/jabberid.h"
#include "xmppcore/stanza.h"

namespace yoohoo_xmppcore {

const QString StanzaParser::ATTRIBUTE_NAME_ID = "id";
const QString StanzaParser::ATTRIBUTE_NAME_TYPE = "type";
const QString StanzaParser::ATTRIBUTE_NAME_TO = "to";
const QString StanzaParser::ATTRIBUTE_NAME_FROM = "from";
const QString StanzaParser::ATTRIBUTE_NAME_LANG = "lang";
const QString StanzaParser::PREFIX_XML = "xml";

XmppObject* StanzaParser::obj() {
	return stanza();
}

bool StanzaParser::processAttributes(QString path, QList<ParsingAttribute> attributes) {
	stanza();

	if (path.indexOf('/') == -1) { // root element
		foreach (ParsingAttribute attribute, attributes) {
			QString prefix = attribute.prefix();
			QString localName = attribute.localName();
			QString value = attribute.value();

			if (PREFIX_XML == prefix && ATTRIBUTE_NAME_LANG == localName) {
				stanza()->setXmlLang(value);
			} else if (!prefix.isEmpty()) {
				return false;
			} else if (ATTRIBUTE_NAME_FROM == localName) {
				JabberId* jidFrom = parseJid(value);
				if (jidFrom) {
					stanza()->setFrom(jidFrom);
				} else {
					return false;
				}	
			} else if (ATTRIBUTE_NAME_TO == localName) {
				JabberId* jidTo = parseJid(value);
				if (jidTo) {
					stanza()->setTo(jidTo);
				} else {
					return false;
				}
			} else if (ATTRIBUTE_NAME_TYPE == localName) {
				if (value == "error") {
					stanza()->_d->type = "error";
				} else {
					setType(value);
				}
			} else if (ATTRIBUTE_NAME_ID == localName) {
				stanza()->setId(value);
			} else {
				return false;
			}		
		}

		return true;
	} else {
		return doProcessAttributes(path, attributes);
	}
}

JabberId* StanzaParser::parseJid(QString jid) {
	JabberId* jabberId = new JabberId;
	if (jabberId->fromString(jid)) {
		return jabberId;
	} else {
		return 0;
	}
}

bool StanzaParser::processEmbeddedObject(ProtocolKey protocolKey, XmppObject* obj) {
	if (!doProcessEmbeddedObject(protocolKey, obj)) {
		return false;
	}

	if (obj != 0) {
		stanza()->setObj(obj);
	}

	return true;
}

bool StanzaParser::doProcessAttributes(QString path, QList<ParsingAttribute> attributes) {
	return true;
}

bool StanzaParser::doProcessEmbeddedObject(ProtocolKey protocolKeys, XmppObject* obj) {
	return true;
}

}
